package Gui;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import Logic.LoginInfo;
import Messages.MessagesGetCopy;
import client.LibaryMain;
import javax.swing.JCheckBox;
import javax.swing.JTree;
import javax.swing.JInternalFrame;
import javax.swing.JToolBar;
import javax.swing.filechooser.FileFilter;
import pdf.PDFTrans;
import server.EchoServer;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URL;
/**
 * this class represent the add book interface 
 * @author Ron Shenkerman
 * @author Gabi Revah
 * @author Aviad Almog
 * @author Ivan Onyshchenko
 */
public class AddBook extends JPanel{
	
	public static int j = 0 ; 
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField TitletextField;
	private JTextField AutortextField;
	private JTextField PlacetextField;
	private JTextField EditionNumtextField;
	private JTextField DescriptiontextField;
	private JComboBox<String>  CategorycomboBox;
	private String [] str;
	private JTextField PrintDatetextField;
	private JTextField catalogNumtextField;
	private JTextField buyingDatetextField;
	private ArrayList<String> copystr;
	
	/**
	 *  creates new window of add book 
	 * @param str
	 */
	public AddBook(String[] str) {
		 	
		setBackground(new Color(153, 204, 255));
		this.str=str;
		initComponents();
	
	}
		
/**
 * init the add book window 	
 */

	public void  initComponents() {
		
		JButton btnBack = new JButton("Back");
		btnBack.addActionListener(new java.awt.event.ActionListener() {     // Back button to Subscriber window 
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btnBackActionPerformed(evt);
            
            }

					private void btnBackActionPerformed(ActionEvent evt) {
						// TODO Auto-generated method stub
						MainScreen.cardLayot.show(MainScreen.card, DirectorWindow.roll);
						
					}
				
        });
		
		JLabel lblTitle = new JLabel("Title");
		lblTitle.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		TitletextField = new JTextField();
		TitletextField.setColumns(10);
		
		
		JLabel lblAutor = new JLabel("Autor");
		lblAutor.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		AutortextField = new JTextField();
		AutortextField.setColumns(10);
		
		JLabel lblCategory = new JLabel("Category");
		lblCategory.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		final JComboBox<String>  CategorycomboBox = new JComboBox();
			for ( int i = 1 ; i <= this.str.length-1; i ++)
				CategorycomboBox.addItem(this.str[i]);
					
		JLabel lblPlaceOnShelf = new JLabel("Place on shelf");
		lblPlaceOnShelf.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		PlacetextField = new JTextField();
		PlacetextField.setColumns(10);
		
		JLabel lblWanted = new JLabel("Wanted");
		lblWanted.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		final JComboBox<String> WantedcomboBox = new JComboBox();
		WantedcomboBox.addItem("Yes");
		WantedcomboBox.addItem("No");
		JLabel lblEditionNum = new JLabel("Edition Number");
		lblEditionNum.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		JLabel lblDescription = new JLabel("Description");
		lblDescription.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		EditionNumtextField = new JTextField();
		EditionNumtextField.setColumns(10);
		
		DescriptiontextField = new JTextField();
		DescriptiontextField.setColumns(10);
		
		JButton btnConfirm = new JButton("Confirm");
		

		btnConfirm.addActionListener(new java.awt.event.ActionListener() {     // Confirm Button in order to add new subscriber action listener 
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	btnConfirmActionPerformed(evt);
            
            }

					private void btnConfirmActionPerformed(ActionEvent evt) {
						// TODO Auto-generated method stub
						System.out.println("Adding a new book to DB" );
						
						
						if(j==0){
						
						if (TitletextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter a Title  ");
								 
						}
						else if (AutortextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter an Autor  ");
								
						}
						else if (PlacetextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter an Place on shelf  ");
								
						}
						else if (EditionNumtextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter an Edition Number  ");
								
						}
						
						else if (PrintDatetextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter an Print date  ");
								
						}
						
						else if (catalogNumtextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter a Catalog number ");
								
						}
						else if (buyingDatetextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter a Buing date ");
								
						}
						else if (DescriptiontextField.getText().equals("") ) 
						{
							JOptionPane.showMessageDialog(null, "Please enter a Description ");
								
						}
						
						
						else	if (    (!(TitletextField.getText().equals("") ) ) || (!(AutortextField.getText().equals("") ) )   || (!(PlacetextField.getText().equals("") ))||
								(!(EditionNumtextField.getText().equals("") ) )|| (!(PrintDatetextField.getText().equals("") )  )|| (!(catalogNumtextField.getText().equals("") )  )
								|| (!(buyingDatetextField.getText().equals("") ) ))
						
						{
							
						
						String wanted = (String) WantedcomboBox.getSelectedItem();
						String category = (String) CategorycomboBox.getSelectedItem();   // casting to comboBox in order to send dtring 
						
						
						ArrayList<String> Arr=new ArrayList<String>();
				        Arr.add("AddBook");
				        Arr.add("0");
				        Arr.add(TitletextField.getText());
				        Arr.add(AutortextField.getText());
				        Arr.add(category);
				        Arr.add(PlacetextField.getText());
				        Arr.add(wanted);
				        Arr.add(EditionNumtextField.getText());
				        Arr.add(PrintDatetextField.getText());
				        Arr.add(catalogNumtextField.getText());
				        Arr.add(buyingDatetextField.getText());
				        Arr.add(DescriptiontextField.getText());
					
				         
				        LibaryMain.chat.handleMessageFromGui(Arr);
				    
				        j=0;
						}
						}
						else{
							
						
							System.out.println(j );
							ArrayList<String> Arr=new ArrayList<String>();
					        Arr.add("AddBook");
					        Arr.add("1");
					        Arr.add(TheBookIsCopy.Copyname);
					        Arr.add(buyingDatetextField.getText());
					        LibaryMain.chat.handleMessageFromGui(Arr);
							
					        j=1;
							
						}
					}
				
        });
		
		JButton btnLogout = new JButton("Logout");
		
		btnLogout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ArrayList<String> Arr=new ArrayList<String>();
				Arr.add("Logout");
				Arr.add("Worker");
				Arr.add(LoginInfo.UserName);
				LibaryMain.chat.handleMessageFromGui(Arr);
				MainScreen.cardLayot.show(MainScreen.card, "Login");
				
			}
		});
		
		JLabel lblPrintDate = new JLabel("Print Date");
		lblPrintDate.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		PrintDatetextField = new JTextField();
		PrintDatetextField.setColumns(10);
		
		JLabel lblCatalogNumber = new JLabel("Catalog Number");
		lblCatalogNumber.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		catalogNumtextField = new JTextField();
		catalogNumtextField.setColumns(10);
		
		JLabel lblBuyingdate = new JLabel("Buying Date");
		lblBuyingdate.setFont(new Font("Tahoma", Font.BOLD, 15));
		
		buyingDatetextField = new JTextField();
		buyingDatetextField.setColumns(10);
		
		JCheckBox chckbxThisBookIs = new JCheckBox("This Book is a copy of another book");
		chckbxThisBookIs.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent arg0) {
			
				if (j==0 ){
					catalogNumtextField.enable(false);
					PrintDatetextField.enable(false);
					DescriptiontextField.enable(false);
					TitletextField.enable(false);
					AutortextField.enable(false);
					PlacetextField.enable(false);
					EditionNumtextField.enable(false);
					WantedcomboBox.enable(false);
					CategorycomboBox.enable(false);
					ArrayList<String> Arr=new ArrayList<String>();
			        Arr.add("IsCopy");
			        LibaryMain.chat.handleMessageFromGui(Arr);
			        j++;
			
				}
				else {
					catalogNumtextField.enable(true);
					PrintDatetextField.enable(true);
					DescriptiontextField.enable(true);
					TitletextField.enable(true);
					AutortextField.enable(true);
					PlacetextField.enable(true);
					EditionNumtextField.enable(true);
					WantedcomboBox.enable(true);
					CategorycomboBox.enable(true);
					j--;
					repaint();
				}
			//	j++;
				
			}
		});
		
	//	j=0;
		
		
		
		
		JButton jBtnSave = new JButton("Upload Content Menu");
		jBtnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				
				jBtnSave_actionPerformed(arg0);   
			}
		});
		
		
		
		
		jBtnSave.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 15));
		
		GroupLayout groupLayout = new GroupLayout(this);
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(80)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(lblTitle)
								.addComponent(lblAutor)
								.addComponent(lblWanted)
								.addComponent(lblCategory)
								.addComponent(lblEditionNum)
								.addComponent(lblPlaceOnShelf)
								.addComponent(lblDescription)
								.addComponent(lblPrintDate)
								.addComponent(lblCatalogNumber)
								.addComponent(lblBuyingdate))
							.addGap(31)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(buyingDatetextField, GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
								.addComponent(catalogNumtextField, GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
								.addComponent(PrintDatetextField, GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
								.addComponent(CategorycomboBox, Alignment.TRAILING, 0, 695, Short.MAX_VALUE)
								.addComponent(EditionNumtextField, GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
								.addComponent(WantedcomboBox, 0, 695, Short.MAX_VALUE)
								.addComponent(TitletextField, GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
								.addComponent(PlacetextField, GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
								.addComponent(AutortextField, 135, 695, Short.MAX_VALUE)
								.addComponent(DescriptiontextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
								.addComponent(chckbxThisBookIs))
							.addPreferredGap(ComponentPlacement.RELATED))
						.addGroup(groupLayout.createSequentialGroup()
							.addContainerGap()
							.addComponent(btnBack)
							.addPreferredGap(ComponentPlacement.RELATED, 766, Short.MAX_VALUE)
							.addComponent(btnConfirm)
							.addGap(12)))
					.addGap(16)
					.addComponent(btnLogout))
				.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
					.addContainerGap(443, Short.MAX_VALUE)
					.addComponent(jBtnSave, GroupLayout.PREFERRED_SIZE, 265, GroupLayout.PREFERRED_SIZE)
					.addGap(305))
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.TRAILING)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
						.addComponent(AutortextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addGroup(groupLayout.createSequentialGroup()
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblTitle)
								.addComponent(TitletextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(lblAutor)))
					.addGap(10)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(lblCategory)
						.addComponent(CategorycomboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(PlacetextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblPlaceOnShelf))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblWanted)
						.addComponent(WantedcomboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(EditionNumtextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblEditionNum))
					.addGap(18)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(lblPrintDate)
						.addComponent(PrintDatetextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(lblCatalogNumber)
						.addComponent(catalogNumtextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(lblBuyingdate)
						.addComponent(buyingDatetextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addGap(18)
					.addComponent(chckbxThisBookIs)
					.addGap(34)
					.addComponent(jBtnSave, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
					.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addComponent(lblDescription)
						.addComponent(DescriptiontextField, GroupLayout.PREFERRED_SIZE, 139, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnConfirm)
						.addComponent(btnLogout)
						.addComponent(btnBack))
					.addGap(21))
		);
		setLayout(groupLayout);
		
		
		
		
		
		
	}
	
	/**
	 * init the combobox with categories 
	 * @param str
	 */
	public void addcombo (String[] str)
	{
		for ( int i = 1 ; i <= str.length-1; i ++)
			this.CategorycomboBox.addItem(str[i]);
	
		
	}
	
	
	
	public void jBtnSave_actionPerformed(ActionEvent e)   
	  {   
	    try  
	    {   JFileChooser saveFile = new JFileChooser();//new open dialog   
	         saveFile.addChoosableFileFilter(new FileFilter()//adds new filter into list   
	     {   
	       String description = "pdf Files (*.pdf)";//the filter you see   
	       String extension = "pdf";
	       
			       public String getDescription()   
			       {   
			         return description;   
			       }   
			       
	       public boolean accept(File f)   
	       {   
	         if(f == null) return false;   
	         if(f.isDirectory()) return true;   
	         return f.getName().toLowerCase().endsWith(extension);   
	       }
		
	     });   
	    
	   int flag = saveFile.showOpenDialog(null);      
	   if (flag == saveFile.APPROVE_OPTION)
	   {
		   byte[] byteArray=null;

		   File file = saveFile.getSelectedFile();
		   String filename = file.getName(); 
		  
		   saveFile.setSelectedFile(file);
		 
		   
	        Socket socket = new Socket(LibaryMain.host, PDFTrans.PORT);  
	        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());  
	        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());  
	  
	        oos.writeObject(file.getName());  
	  
	        FileInputStream fis = new FileInputStream(file);  
	        byte [] buffer = new byte[PDFTrans.BUFFER_SIZE];  
	        Integer bytesRead = 0;  
	  
	        while ((bytesRead = fis.read(buffer)) > 0) {  
	            oos.writeObject(bytesRead);  
	            oos.writeObject(Arrays.copyOf(buffer, buffer.length));  
	        }  
	  
	        oos.close();  
	        ois.close();  
	        //System.exit(0);  
	        /*
		   //ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		  // InputStream inputStream  = classLoader.getResourceAsStream(filename);
		 
		   InputStream inputStream = new FileInputStream(file);
		   String inputStreamToString = inputStream.toString();
		   byteArray = inputStreamToString.getBytes();
           inputStream.close();

		   
		   
		   
		//   URL url = classLoader.getResource(filename);
		  // File PdfFile = new File(url.toURI().getPath());
		   
			FileOutputStream fos = new FileOutputStream(new File(new File(saveFile.getSelectedFile().getPath()).getCanonicalPath()));
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			bos.write(byteArray, 0, byteArray.length);
		   bos.flush();
		   bos.close();                                                                      */
	   }
	   	//    saveFile.setCurrentDirectory(new File("*.pdf"));   
	   	//  int result=saveFile.showOpenDialog(this);   
	    //String strFileName=saveFile.getSelectedFile().getName();   


	    
	    }   
	    catch(Exception er)   
	    {   
	    
	    }  

	
	  }
	
}
